package security;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

public class MyLoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        String url = request.getRequestURI();

        // 获取用户名、密码数据
        String username = obtainUsername(request);

        //根据用户名获取真实用户信息
        SecurityUser user = new SecurityUser();
//		SecurityUser user = this.securityUserSpecMapper.selectByUsername(username);

        // 判断用户相关信息
        if (user == null) {
            throw new UsernameNotFoundException("用户" + username + "不存在");
        }

        //假设需要进行用户权限的判断
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        if (url.contains("admin")) {
            // 如果通过后台链接，只有admin角色能够登录
            if (!authorities.contains("ROLE_ADMIN")) {
                throw new BadCredentialsException("对不起，您没有权限通过此页面登录!");
            }
        } else {
            // 如果通过前台链接，只有front角色能够登录
            if (!authorities.contains("ROLE_FRONT")) {
                throw new BadCredentialsException("对不起，您没有权限通过此页面登录!");
            }
        }
        return super.attemptAuthentication(request, response);
    }

}
